package com.ouken.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import com.ouken.asynTask.AsynUpdate;
import com.ouken.tool.ConnectServer;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;

public class RefreshRoomlistService extends Service {

	private final IBinder mBinder = new LocalBinder();
	
	public class LocalBinder extends Binder{
		public RefreshRoomlistService getService(){
			return RefreshRoomlistService.this;
		}
	}
	private String httpUrl;
	private List params;
	private Bundle bundleToBroadcast;
	private Intent intentToBroadcast;
	private AsynUpdate asynUpdate;
	private Thread udataRoomlist;
	private Boolean isRunning;

	@Override
	public void onDestroy() {
		//asynUpdate.cancel(true);
		//objHandler.removeCallbacks(mTasks);
		System.out.println("Service destroy");
		isRunning = false;
		super.onDestroy();
	}
	
	

	@Override
	public boolean onUnbind(Intent intent) {
		
		isRunning = false;
		System.out.println("Service onUnbind");
		return super.onUnbind(intent);
	}

	@Override
	public IBinder onBind(Intent intent) {
		
		Bundle bundle = new Bundle();
		bundle = intent.getExtras();
		String roomname = bundle.getString("roomname");
		this.httpUrl = "http://"+ConnectServer.getServerAdd()+"/getroomlist";
		
		params = new ArrayList();
		params.add(new BasicNameValuePair("roomname", roomname.toString()));
		params.add(new BasicNameValuePair("ParamEnd", "ParamEndParamEndParamEnd"));
		
		bundleToBroadcast = new Bundle();
		intentToBroadcast = new Intent("com.updataReceiver");
		
		System.out.println("Service onBind");
		
		udataRoomlist = new Thread(new Runnable() {  
            @Override  
            public void run() {  
            	while(isRunning){
	                System.out.println("udataRoomlistThread is running");
	                if(isRunning){
		        		sendBroadcast( new Intent("open.ProcessTitleBar"));
		        		String result = ConnectServer.connect(httpUrl,params);
		        		if(result == null) continue;
		                bundleToBroadcast.putString("result", result);
		            	intentToBroadcast.putExtras(bundleToBroadcast);
		        		sendBroadcast(intentToBroadcast);
	                }
	                
	                try {  
	                    Thread.sleep(5000);  
	                } catch (Exception e) {  
	                    e.printStackTrace();  
	                }
	        		
             }
            	
            	System.out.println("udataRoomlistThread  stop");
            }
        });  
		isRunning = true;
		udataRoomlist.start();
		
		return mBinder;
	}

	

	
	
	
	

}
